package handlers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"runtime"
	"time"

	"github.com/gorilla/mux"
	"github.com/shirou/gopsutil/v3/host"
	
	"skedule-backend/database"
	"skedule-backend/scheduler"
	"skedule-backend/utils"
)

// SettingsHandler 设置处理器
type SettingsHandler struct {
	scheduler *scheduler.Scheduler
}

// NewSettingsHandler 创建设置处理器
func NewSettingsHandler(scheduler *scheduler.Scheduler) *SettingsHandler {
	return &SettingsHandler{scheduler: scheduler}
}

// SystemInfo 系统信息
type SystemInfo struct {
	Version     string `json:"version"`
	Uptime      string `json:"uptime"`
	ActiveTasks int    `json:"activeTasks"`
	TotalTasks  int64  `json:"totalTasks"`
	OS          string `json:"os"`
	Arch        string `json:"arch"`
	Memory      string `json:"memory"`
}

// GetSettings 获取系统设置
func (h *SettingsHandler) GetSettings(w http.ResponseWriter, r *http.Request) {
	var settings database.Settings
	if err := database.DB.First(&settings).Error; err != nil {
		Error(w, CodeDatabaseError, utils.T("settings.get.failed"))
		return
	}

	Success(w, settings)
}

// UpdateSettings 更新系统设置
func (h *SettingsHandler) UpdateSettings(w http.ResponseWriter, r *http.Request) {
	var updateData database.Settings
	if err := json.NewDecoder(r.Body).Decode(&updateData); err != nil {
		Error(w, CodeBadRequest, utils.T("settings.request.invalid"))
		return
	}

	// 获取现有设置
	var settings database.Settings
	if err := database.DB.First(&settings).Error; err != nil {
		Error(w, CodeDatabaseError, utils.T("settings.current.get.failed"))
		return
	}

	// 更新字段
	settings.SystemName = updateData.SystemName
	settings.MaxConcurrentTasks = updateData.MaxConcurrentTasks
	settings.LogRetentionDays = updateData.LogRetentionDays
	settings.EnableFailureNotification = updateData.EnableFailureNotification
	settings.EmailAddress = updateData.EmailAddress
	settings.UpdatedAt = time.Now()

	// 保存设置
	if err := database.DB.Save(&settings).Error; err != nil {
		Error(w, CodeDatabaseError, utils.T("settings.save.failed"))
		return
	}

	SuccessWithMsg(w, utils.T("settings.update.success"), settings)
}

// GetSystemInfo 获取系统信息
func (h *SettingsHandler) GetSystemInfo(w http.ResponseWriter, r *http.Request) {
	// 获取任务统计
	var totalTasks int64
	database.DB.Model(&database.Task{}).Count(&totalTasks)

	activeTasks := h.scheduler.GetRunningTasks()

	// 获取系统信息
	var uptime string
	if hostInfo, err := host.Info(); err == nil {
		uptimeDuration := time.Duration(hostInfo.Uptime) * time.Second
		uptime = formatDuration(uptimeDuration)
	} else {
		uptime = utils.T("network.ip.unknown")
	}

	// 获取内存信息
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	memory := formatBytes(m.Alloc)

	info := SystemInfo{
		Version:     "1.0.0",
		Uptime:      uptime,
		ActiveTasks: activeTasks,
		TotalTasks:  totalTasks,
		OS:          runtime.GOOS,
		Arch:        runtime.GOARCH,
		Memory:      memory,
	}

	Success(w, info)
}

// formatDuration 格式化时间间隔
func formatDuration(d time.Duration) string {
	days := int(d.Hours()) / 24
	hours := int(d.Hours()) % 24
	minutes := int(d.Minutes()) % 60

	if days > 0 {
		return fmt.Sprintf(utils.T("handler.duration.format.days"), days, hours, minutes)
	} else if hours > 0 {
		return fmt.Sprintf(utils.T("handler.duration.format.hours"), hours, minutes)
	} else {
		return fmt.Sprintf(utils.T("handler.duration.format.minutes"), minutes)
	}
}

// formatBytes 格式化字节数
func formatBytes(bytes uint64) string {
	const unit = 1024
	if bytes < unit {
		return fmt.Sprintf("%d B", bytes)
	}
	div, exp := uint64(unit), 0
	for n := bytes / unit; n >= unit; n /= unit {
		div *= unit
		exp++
	}
	return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
}

// SetupSettingsRoutes 设置系统设置路由
func SetupSettingsRoutes(router *mux.Router, settingsHandler *SettingsHandler) {
	settingsRouter := router.PathPrefix("/settings").Subrouter()
	settingsRouter.HandleFunc("", settingsHandler.GetSettings).Methods("GET")
	settingsRouter.HandleFunc("", settingsHandler.UpdateSettings).Methods("PUT")
	
	// 系统信息路由
	router.HandleFunc("/system/info", settingsHandler.GetSystemInfo).Methods("GET")
} 